package cn.iocoder.yudao.module.promotion.service.yearcardconfig;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.promotion.controller.admin.yearcardconfig.vo.YearCardConfigPageReqVO;
import cn.iocoder.yudao.module.promotion.controller.admin.yearcardconfig.vo.YearCardConfigSaveReqVO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.yearcardconfig.YearCardConfigDO;
import cn.iocoder.yudao.module.promotion.dal.mysql.yearcardconfig.YearCardConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.YEAR_CARD_CONFIG_NOT_EXISTS;

/**
 * 年卡配置 Service 实现类
 *
 * @author 万民匠心
 */
@Service
@Validated
public class YearCardConfigServiceImpl implements YearCardConfigService {

    @Resource
    private YearCardConfigMapper yearCardConfigMapper;

    @Override
    public Long createYearCardConfig(YearCardConfigSaveReqVO createReqVO) {
        // 插入
        YearCardConfigDO yearCardConfig = BeanUtils.toBean(createReqVO, YearCardConfigDO.class);
        yearCardConfigMapper.insert(yearCardConfig);
        // 返回
        return yearCardConfig.getId();
    }

    @Override
    public void updateYearCardConfig(YearCardConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateYearCardConfigExists(updateReqVO.getId());
        // 更新
        YearCardConfigDO updateObj = BeanUtils.toBean(updateReqVO, YearCardConfigDO.class);
        yearCardConfigMapper.updateById(updateObj);
    }

    @Override
    public void deleteYearCardConfig(Long id) {
        // 校验存在
        validateYearCardConfigExists(id);
        // 删除
        yearCardConfigMapper.deleteById(id);
    }

    private void validateYearCardConfigExists(Long id) {
        if (yearCardConfigMapper.selectById(id) == null) {
            throw exception(YEAR_CARD_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public YearCardConfigDO getYearCardConfig(Long id) {
        return yearCardConfigMapper.selectById(id);
    }

    @Override
    public YearCardConfigDO getYearCardConfig() {
        List<YearCardConfigDO> result = yearCardConfigMapper.selectList();
        return CollUtil.isEmpty(result) ? null : result.get(0);
    }

    @Override
    public PageResult<YearCardConfigDO> getYearCardConfigPage(YearCardConfigPageReqVO pageReqVO) {
        return yearCardConfigMapper.selectPage(pageReqVO);
    }

}